package com.dq.offer;

import com.dq.utils.CreateArray;

import java.util.Arrays;

/**
 * @Author: Dang Qi
 * @Date: 2021/3/10  19:37
 * @Description:
 */
public class PrintMatrixSort {
    public static void main(String[] args) {
        Solution solution = new PrintMatrixSort().new Solution();
        String s = "[[1,2,3,4],[5,6,7,8],[9,10,11,12]]";
        int[][] matrix = (int[][]) CreateArray.genIntArray(s);
        for(int[] m: matrix){
            System.out.println(Arrays.toString(m));
        }
        System.out.println(Arrays.toString(solution.spiralOrder(matrix)));
    }
    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            // 0: right, 1: left, 2: up, 3: down;
            int m = matrix.length, n = matrix[0].length;
            int direct = 0;
            int[] ans = new int[m * n];

            int i = 0, j = 0;
            int len = 0;
            while(len < ans.length){
                System.out.printf("len=%d, (%d,%d)\n", len, i, j);
                ans[len++] = matrix[i][j];
                switch(direct){
                    case 0: //right
                        if(i+j == n-1) {
                            i++;
                            direct = 3;
                        }
                        else j++;
                        break;
                    case 1: //left
                        if(i+j == m-1) {
                            i--;
                            direct = 2;
                        }
                        else j--;
                        break;
                    case 2: //up
                        if(i-j==1){
                            j++;
                            direct = 0;
                        }
                        else i--;
                        break;
                    case 3: //down
                        if(i-j== m-n){
                            j--;
                            direct = 1;
                        }
                        else i++;
                }
            }
            return ans;
        }
    }
}
